'use client';

import React, { useState, useEffect } from 'react';
import { useCollaboration } from '@/hooks/use-collaboration';
import { useSocket } from '@/hooks/use-socket';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Textarea } from '@/components/ui/textarea';
import { ScrollArea } from '@/components/ui/scroll-area';
import { format } from 'date-fns';
import { MessageSquare, Send, Check } from 'lucide-react';
import { CommentData } from '@/types/socket';
import { toast } from '@/components/ui/use-toast';

interface DocumentCommentsProps {
  documentId: string;
  projectId: string;
  className?: string;
}

export function DocumentComments({ documentId, projectId, className = '' }: DocumentCommentsProps) {
  const { socket, isConnected } = useSocket();
  const [comments, setComments] = useState<CommentData[]>([]);
  const [newComment, setNewComment] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [selectedCommentId, setSelectedCommentId] = useState<string | null>(null);
  const [replyContent, setReplyContent] = useState('');
  
  // 加载评论
  useEffect(() => {
    // 在实际项目中，这里应该从API加载评论
    // 这里使用模拟数据
    const mockComments: CommentData[] = [
      {
        id: 'comment-1',
        projectId: 'project-1',
        docId: documentId,
        content: '这个段落需要更多详细说明',
        author: {
          id: 'user-1',
          name: '张三',
          image: ''
        },
        timestamp: Date.now() - 3600000,
        status: 'active',
        replies: []
      },
      {
        id: 'comment-2',
        projectId: 'project-1',
        docId: documentId,
        content: '这部分内容可以考虑重新组织',
        author: {
          id: 'user-2',
          name: '李四',
          image: ''
        },
        timestamp: Date.now() - 7200000,
        status: 'active',
        replies: []
      }
    ];
    
    setComments(mockComments);
  }, [documentId]);
  
  // 监听新评论
  useEffect(() => {
    if (!socket || !isConnected) return;
    
    const handleNewComment = (data: CommentData) => {
      if (data.docId !== documentId) return;
      
      setComments(prev => [...prev, data]);
    };
    
    const unsubscribe = socket.onCommentAdded(handleNewComment);
    
    return () => {
      unsubscribe();
    };
  }, [socket, isConnected, documentId]);
  
  // 提交新评论
  const handleSubmitComment = () => {
    if (!newComment.trim() || !socket || !isConnected) return;
    
    setSubmitting(true);
    
    try {
      const commentData: CommentData = {
        id: `comment-${Date.now()}`,
        projectId: 'project-1', // 实际项目中应该使用真实的projectId
        docId: documentId,
        content: newComment.trim(),
        author: {
          id: 'current-user', // 实际项目中应该使用真实的用户ID
          name: '当前用户', // 实际项目中应该使用真实的用户名
          image: ''
        },
        timestamp: Date.now(),
        status: 'active',
        replies: []
      };
      
      // 发送评论
      socket.sendComment(commentData);
      
      // 添加到本地状态
      setComments(prev => [...prev, commentData]);
      
      // 清空输入
      setNewComment('');
      
      toast({
        title: '评论已发送',
        description: '您的评论已成功发送'
      });
    } catch (error) {
      console.error('发送评论失败:', error);
      toast({
        title: '发送失败',
        description: '无法发送评论，请重试',
        variant: 'destructive'
      });
    } finally {
      setSubmitting(false);
    }
  };
  
  // 提交回复
  const handleSubmitReply = (commentId: string) => {
    if (!replyContent.trim() || !socket || !isConnected) return;
    
    try {
      const replyData = {
        id: `reply-${Date.now()}`,
        content: replyContent.trim(),
        author: {
          id: 'current-user', // 实际项目中应该使用真实的用户ID
          name: '当前用户', // 实际项目中应该使用真实的用户名
          image: ''
        },
        createdAt: new Date().toISOString()
      };
      
      // 更新本地状态
      setComments(prev => 
        prev.map(comment => 
          comment.id === commentId
            ? { ...comment, replies: [...(comment.replies || []), replyData] }
            : comment
        )
      );
      
      // 清空输入并关闭回复框
      setReplyContent('');
      setSelectedCommentId(null);
      
      toast({
        title: '回复已发送',
        description: '您的回复已成功发送'
      });
    } catch (error) {
      console.error('发送回复失败:', error);
      toast({
        title: '发送失败',
        description: '无法发送回复，请重试',
        variant: 'destructive'
      });
    }
  };
  
  // 解决评论
  const handleResolveComment = (commentId: string) => {
    setComments(prev => 
      prev.map(comment => 
        comment.id === commentId
          ? { ...comment, status: 'resolved' as const }
          : comment
      )
    );
    
    toast({
      title: '评论已解决',
      description: '评论已标记为已解决'
    });
  };
  
  // 获取用户初始字母（用于头像）
  const getUserInitials = (name: string) => {
    return name
      .split(' ')
      .map(part => part[0])
      .join('')
      .toUpperCase()
      .substring(0, 2);
  };
  
  // 渲染评论列表
  const renderComments = () => {
    if (comments.length === 0) {
      return (
        <div className="py-8 text-center text-muted-foreground">
          <p>暂无评论</p>
        </div>
      );
    }
    
    return (
      <ScrollArea className="h-[400px]">
        <div className="space-y-4 pr-4">
          {comments.map(comment => (
            <Card key={comment.id} className={`p-3 ${comment.status === 'resolved' ? 'bg-muted/30' : ''}`}>
              <div className="flex items-start gap-3">
                <Avatar className="h-8 w-8">
                  {comment.author.image ? (
                    <AvatarImage src={comment.author.image} alt={comment.author.name} />
                  ) : (
                    <AvatarFallback>{getUserInitials(comment.author.name)}</AvatarFallback>
                  )}
                </Avatar>
                
                <div className="flex-1">
                  <div className="flex items-center justify-between">
                    <div>
                      <span className="font-medium">{comment.author.name}</span>
                      <span className="text-xs text-muted-foreground ml-2">
                        {format(new Date(comment.timestamp), 'yyyy-MM-dd HH:mm')}
                      </span>
                    </div>
                    
                    {comment.status === 'active' && (
                      <Button
                        size="sm"
                        variant="ghost"
                        className="h-7 px-2"
                        onClick={() => handleResolveComment(comment.id)}
                      >
                        <Check className="h-4 w-4 mr-1" />
                        <span className="text-xs">解决</span>
                      </Button>
                    )}
                  </div>
                  
                  <p className="mt-1 text-sm">{comment.content}</p>
                  
                  {/* 回复列表 */}
                  {comment.replies && comment.replies.length > 0 && (
                    <div className="mt-3 pl-4 border-l-2 border-muted space-y-3">
                      {comment.replies.map(reply => (
                        <div key={reply.id} className="flex items-start gap-2">
                          <Avatar className="h-6 w-6">
                            {reply.author.image ? (
                              <AvatarImage src={reply.author.image} alt={reply.author.name} />
                            ) : (
                              <AvatarFallback className="text-xs">{getUserInitials(reply.author.name)}</AvatarFallback>
                            )}
                          </Avatar>
                          
                          <div>
                            <div>
                              <span className="text-sm font-medium">{reply.author.name}</span>
                              <span className="text-xs text-muted-foreground ml-2">
                                {format(new Date(reply.createdAt), 'yyyy-MM-dd HH:mm')}
                              </span>
                            </div>
                            <p className="text-sm">{reply.content}</p>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                  
                  {/* 回复框 */}
                  {selectedCommentId === comment.id && comment.status === 'active' && (
                    <div className="mt-3">
                      <Textarea
                        value={replyContent}
                        onChange={(e) => setReplyContent(e.target.value)}
                        placeholder="输入回复..."
                        className="min-h-[80px] text-sm"
                      />
                      <div className="flex justify-end mt-2 gap-2">
                        <Button
                          size="sm"
                          variant="ghost"
                          onClick={() => setSelectedCommentId(null)}
                        >
                          取消
                        </Button>
                        <Button
                          size="sm"
                          onClick={() => handleSubmitReply(comment.id)}
                          disabled={!replyContent.trim()}
                        >
                          回复
                        </Button>
                      </div>
                    </div>
                  )}
                  
                  {/* 回复按钮 */}
                  {selectedCommentId !== comment.id && comment.status === 'active' && (
                    <Button
                      size="sm"
                      variant="ghost"
                      className="mt-2 h-7 px-2"
                      onClick={() => setSelectedCommentId(comment.id)}
                    >
                      <MessageSquare className="h-3 w-3 mr-1" />
                      <span className="text-xs">回复</span>
                    </Button>
                  )}
                </div>
              </div>
            </Card>
          ))}
        </div>
      </ScrollArea>
    );
  };
  
  return (
    <div className={`space-y-4 ${className}`}>
      <div className="flex items-center justify-between">
        <h3 className="text-lg font-medium flex items-center gap-2">
          <MessageSquare className="h-5 w-5" />
          <span>文档评论</span>
        </h3>
      </div>
      
      {renderComments()}
      
      <div className="pt-3 border-t">
        <Textarea
          value={newComment}
          onChange={(e) => setNewComment(e.target.value)}
          placeholder="添加评论..."
          className="min-h-[100px]"
        />
        <div className="flex justify-end mt-2">
          <Button
            onClick={handleSubmitComment}
            disabled={!newComment.trim() || submitting}
          >
            <Send className="h-4 w-4 mr-2" />
            发送评论
          </Button>
        </div>
      </div>
    </div>
  );
} 